<template>
    <el-main>
        <div class="container">
            <el-card style="height: 80px;width: 550px;">
                <!-- 查询条件区域 -->
                <el-form :inline="true" ref="searchForm" class="demo-form-inline" label-width="80px" size="small">
                    <el-form-item>
                        <el-input v-model="searchModel.iconoreName" placeholder="请输入原料名称" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                        <!-- <el-button icon="el-icon-refresh-right">重置</el-button> -->
                        <el-button type="success" icon="el-icon-plus" @click="openAddWindow()">新增</el-button>
                        <!-- 导出excel表格 -->
                        <el-button :loading="downloadLoading" style="margin:0 0 10px 10px;" type="primary"
                            icon="el-icon-document" @click="handleDownload">
                            Export Excel
                        </el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <div style="height: 30px; background-color: transparent;"></div>

        <el-card>
            <!-- 数据表格 selection="selectedData" @selection-change="handleSelectionChange"-->
            <el-table :data="tableData" stripe style="width: 100%" ref="iconoreTable">
                <!-- 添加一个序号列，使用type="index" -->
                <el-table-column type="index" label="序号" label-class-name="bold-header" fixed="left" />
                <!-- 添加一个选择列，使用type="selection" :selectable="checkSelect" prop="isSelected"-->
                <!-- <el-table-column type="selection" width="50" align="center" v-model="tableData.isSelected"></el-table-column> -->

                <!-- <el-table-column type="selection" label="选择" width="60px" :checked=" isSelected "v-model="scope.row.isSelected"/>  -->
                <el-table-column prop="isSelected" type="index" label="选择" width="60px" label-class-name="bold-header">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isSelected" :checked="scope.row.isSelected"
                            @change="updateIsSelected(scope.row)"></el-checkbox>
                    </template>
                </el-table-column>

                <!-- prop:填写数据的属性名称 -->
                <el-table-column prop="iconoreName" label="原料名称" fixed="left" label-class-name="bold-header"
                    width="150px" />
                <el-table-column prop="tfe" label="TFe" label-class-name="bold-header" />
                <el-table-column prop="sio2" label="SiO2" label-class-name="bold-header" />
                <el-table-column prop="ca0" label="CaO" label-class-name="bold-header" />
                <el-table-column prop="mgo" label="MgO" label-class-name="bold-header" />
                <el-table-column prop="al2o3" label="Al2O3" label-class-name="bold-header" />
                <el-table-column prop="p" label="P" label-class-name="bold-header" />
                <el-table-column prop="s" label="S" label-class-name="bold-header" />
                <el-table-column prop="mn" label="Mn" label-class-name="bold-header" />
                <el-table-column prop="h2o" label="H2O" label-class-name="bold-header" />
                <el-table-column prop="burn" label="Burn" label-class-name="bold-header" />
                <el-table-column prop="price" label="价格" label-class-name="bold-header" />
                <el-table-column prop="min" label="下限" label-class-name="bold-header" />
                <el-table-column prop="max" label="上限" label-class-name="bold-header" />
                <el-table-column label="操作" width="200" label-position="center" label-class-name="bold-header">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)" icon="el-icon-s-promotion">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
                            icon="el-icon-delete-solid">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- <el-table :data="tableData" style=" margin-bottom: 20px" row-key="id">
            
        </el-table> -->

            <!-- 添加和修改窗口 -->
            <system-dialog :title="deptDialog.title" :visible="deptDialog.visible" :width="deptDialog.width"
                :height="deptDialog.height" @onClose="onClose" @onConfirm="onConfirm">
                <div slot="content">
                    <el-form :model="iconore" ref="deptForm" :rules="rules" label-width="100px" :inline="true" size="small">
                        <el-form-item label="原料名称" prop="iconoreName">
                            <el-input v-model="iconore.iconoreName"></el-input>
                        </el-form-item>
                        <el-form-item label="TFe含量" prop="tfe">
                            <el-input v-model="iconore.tfe"></el-input>
                        </el-form-item>
                        <el-form-item label="SiO2含量" prop="sio2">
                            <el-input v-model="iconore.sio2"></el-input>
                        </el-form-item>
                        <el-form-item label="CaO含量" prop="ca0">
                            <el-input v-model="iconore.ca0"></el-input>
                        </el-form-item>
                        <el-form-item label="MgO含量" prop="mgo">
                            <el-input v-model="iconore.mgo"></el-input>
                        </el-form-item>
                        <el-form-item label="Al2O3含量" prop="al2o3">
                            <el-input v-model="iconore.al2o3"></el-input>
                        </el-form-item>
                        <el-form-item label="P含量" prop="p">
                            <el-input v-model="iconore.p"></el-input>
                        </el-form-item>
                        <el-form-item label="S含量" prop="s">
                            <el-input v-model="iconore.s"></el-input>
                        </el-form-item>
                        <el-form-item label="Mn含量" prop="mn">
                            <el-input v-model="iconore.mn"></el-input>
                        </el-form-item>
                        <el-form-item label="H2O含量" prop="h2o">
                            <el-input v-model="iconore.h2o"></el-input>
                        </el-form-item>
                        <el-form-item label="Burn含量" prop="burn">
                            <el-input v-model="iconore.burn"></el-input>
                        </el-form-item>
                        <el-form-item label="价格" prop="price">
                            <el-input v-model="iconore.price"></el-input>
                        </el-form-item>
                        <el-form-item label="下限" prop="min">
                            <el-input v-model="iconore.min"></el-input>
                        </el-form-item>
                        <el-form-item label="上限" prop="max">
                            <el-input v-model="iconore.max"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
            </system-dialog>

            <!-- 分页器 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                :page-sizes="[1, 2, 5, 10]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
                :total="total" style="margin-top: 10px">
            </el-pagination>
        </el-card>


        <div style="height: 10px; background-color: white;"></div>

        <!-- 添加一个路由跳转，使用router-link -->
        <!-- <router-link :to="{ path: '/orebleeding', query: { oreData: JSON.stringify(selectedData) } }">
            <el-button type="primary" style="height: 40px; padding: 6px;"
                icon="el-icon-circle-check">添加所选铁矿石至配料界面</el-button>
        </router-link> -->
    </el-main>
</template>

<script>
//导入department脚本文件
import departmentApi from "@/api/department";
import iconoreApi from "@/api/iconore";
//导入对话框组件
import SystemDialog from "@/components/system/SystemDialog1.vue";
import axios from 'axios';

export default {
    name: "iconore",
    components: {
        SystemDialog,
    },
    data() {
        return {
            downloadLoading: false,//导出时按钮
            searchModel: {
                iconoreName: "", //铁矿石名称
            },
            selectedData: [], // 存储被选择的原料的数据
            tableData: [],//表格数据
            // isSelect: 1,
            // isSelected: 1,
            page: 1,
            size: 10,
            total: 1,
            deptDialog: {
                title: "",
                visible: false,
                width: 380,
                height: 500,
            },
            iconore: {
                id: "",
                iconoreName: "",
                tfe: "",
                sio2: "",
                ca0: "",
                mgo: "",
                al2o3: "",
                p: "",
                s: "",
                mn: "",
                h2o: "",
                burn: "",
                price: "",
                isSelected: "",
                min: "",
                max: ""
            },
            rules: {
                iconoreName: [
                    { required: true, message: "请输入原料名称", trigger: "change" },
                ],
                tfe: [{ required: true, message: "请输入内容", trigger: "change" }],
                sio2: [{ required: true, message: "请输入内容", trigger: "change" }],
                ca0: [{ required: true, message: "请输入内容", trigger: "change" }],
                mgo: [{ required: true, message: "请输入内容", trigger: "change" }],
                al2o3: [{ required: true, message: "请输入内容", trigger: "change" }],
                p: [{ required: true, message: "请输入内容", trigger: "change" }],
                s: [{ required: true, message: "请输入内容", trigger: "change" }],
                mn: [{ required: true, message: "请输入内容", trigger: "change" }],
                h2o: [{ required: true, message: "请输入内容", trigger: "change" }],
                burn: [{ required: true, message: "请输入内容", trigger: "change" }],
                price: [{ required: true, message: "请输入内容", trigger: "change" }],
                min: [{ required: true, message: "请输入内容", trigger: "change" }],
                max: [{ required: true, message: "请输入内容", trigger: "change" }],
            },

        };
    },
    //初始化时调用
    created() {
        //调用查询部门列表
        this.search();
        // console.log(this.selectedData);
        this.selectedData = "";
    },

    methods: {

        /**
         *更新选择状态
         */
        async updateIsSelected(row) {


            //数据回显
            this.$objCopy(row, this.iconore);
            console.log(this.iconore);
            if (this.iconore.isSelected) {
                this.iconore.isSelected = 1;
            } else {
                this.iconore.isSelected = 0;
            }
            console.log(this.iconore);
            // let res = await iconoreApi.addIconore(this.iconore);
            let res = await iconoreApi.updateIconore(this.iconore);
            if (res.success) {
                //提示成功
                // this.$message.success("添加成功");
                //刷新数据
                this.search();
            } else {
                this.$message.error("添加失败");
            }
            window.location.reload();

        },

        /**
         * 根据is_selected属性确定选择框状态
         */
        // checkSelect(row) {
        //     let isChecked = true;
        //     if (row.isSelected == 0) {
        //         // 判断里面是否存在某个参数
        //         isChecked = true;
        //     } else {
        //         isChecked = false;
        //     }
        //     return isChecked;
        // },


        // 定义一个函数，用来处理选择项变化时的逻辑
        handleSelectionChange(selection) {
            // 将选择的行的数据赋值给selectedData数组
            this.selectedData = selection;
            // 打印或发送选中的数据
            console.log(this.selectedData);
        },

        /**
         * 导出excel数据
         */
        handleDownload() {
            this.downloadLoading = true
            import('@/vendor/Export2Excel').then(excel => {
                const tHeader = ['原料名称', 'TFe', 'SiO2', 'CaO', 'MgO', 'Al2O3', 'P', 'S', 'Mn', 'H2O', 'Burn']
                const filterVal = ['iconoreName', 'tfe', 'sio2', 'ca0', 'mgo', 'al2o3', 'p', 's', 'mn', 'h2o', 'burn']
                const list = this.tableData
                const data = this.formatJson(filterVal, list)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: '原料信息.xlsx',
                    autoWidth: this.autoWidth,
                    bookType: 'xlsx'
                })
                this.downloadLoading = false
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },

        //选择时传递数据
        handleSelect(row) {
            console.log("调用handleChange方法")
            // 手动修改row.checked的值，以反映选择框的状态
            // row.checked = !row.checked
            // 处理接收到的原料数据
            console.log(row)
            // console.log(row.checked)
            if (row) {
                console.log("进入确认方法")
                // 如果该行被选择，将该行的数据添加到selectedData数组中
                this.selectedData.push(row)
                console.log(this.selectedData)
            } else {
                console.log("取消确认")
                // 如果该行被取消选择，将该行的数据从selectedData数组中删除
                let index = this.selectedData.indexOf(row)
                if (index > -1) {
                    this.selectedData.splice(index, 1)
                }
            }
            console.log(this.selectedData)
        },


        /**
         * 编辑部门
         */
        handleEdit(row) {
            //数据回显
            this.$objCopy(row, this.iconore);
            //设置窗口的标题
            this.deptDialog.title = "编辑铁矿石数据";
            //显示窗口
            this.deptDialog.visible = true;
        },
        /**
         * 删除原料
         */
        async handleDelete(row) {
            //确认是否删除
            let confirm = window.confirm("确认要删除该数据吗？");
            if (confirm) {
                //发送删除请求
                let res = await iconoreApi.deleteIconore({ id: row.id });
                if (res.success) {
                    //提示成功
                    this.$message.success(res.message);
                    //刷新数据
                    this.search();
                } else {
                    this.$message.error(res.message);
                }
            }

        },

        /**
         * 查询部门列表
         */
        async search() {
            //发送查询请求
            // let res = await departmentApi.getDepartmentList(this.departmentName)
            // .then获取请求成功，.catch获取请求失败，并抛出异常，停止往下执行
            await iconoreApi
                .findIconoreList(this.searchModel)
                .then((res) => {
                    //查看请求成功的数据
                    console.log("res:", res);
                    if (res.success) {
                        // this.tableData = res.data;
                        this.total = res.data.length;
                        let start = (this.page - 1) * this.size; // 计算当前页的起始索引
                        let end = start + this.size; // 计算当前页的结束索引
                        this.tableData = res.data.slice(start, end);
                        this.isSelected = this.tableData.isSelected;
                        // console.log(this.isSelected);
                        console.log(this.tableData)
                    }
                })
                .catch((err) => {
                    // ElMessage.error("请求失败")
                    throw new Error("请求失败");
                });
            // console.log(res)
            // //判断是否成功
            // if (res.success) {
            //     this.tableData = res.data
            // }
        },

        /**
         * 打开添加窗口
         */
        openAddWindow() {
            //清空表单数据,第一个参数是表单的ref值，后面一个参数是表单数据
            this.$resetForm("deptForm", this.iconore);

            this.deptDialog.title = "新增铁矿石";
            this.deptDialog.visible = true;
        },

        /**
         * 窗口的关闭事件
         */
        onClose() {
            this.deptDialog.visible = false;
        },
        /**
         * 窗口确认事件
         */
        onConfirm() {
            //进行表单验证
            this.$refs.deptForm.validate(async (valid) => {
                //如果验证通过
                if (valid) {
                    let res = null;

                    //判断当前是新增还是修改（判断条件，判断当前dept对象的id属性是否为空）
                    //为空发送新增请求，不为空发送修改请求
                    if (this.iconore.id === "") {
                        //发送添加请求
                        if (this.iconore.isSelected) {
                            this.iconore.isSelected = 1;
                        } else {
                            this.iconore.isSelected = 0;
                        }
                        res = await iconoreApi.addIconore(this.iconore);
                    } else {
                        //发送修改请求
                        console.log(this.iconore);
                        if (this.iconore.isSelected) {
                            this.iconore.isSelected = 1;
                        } else {
                            this.iconore.isSelected = 0;
                        }
                        res = await iconoreApi.updateIconore(this.iconore);
                    }

                    if (res.success) {
                        //提示成功
                        this.$message.success(res.message);
                        //刷新数据
                        this.search();
                        //关闭窗口
                        this.deptDialog.visible = false;
                    } else {
                        this.$message.error(res.message);
                    }
                }
            });
        },

        /**
         * 页面大小改变时分页器操作
         */
        handleSizeChange(val) {
            this.size = val;
            this.search();
        },
        /**
         * 当前页码改变时分页器操作
         */
        handleCurrentChange(val) {
            this.page = val;
            this.search();
        },
    },
};
</script>

<style>
.bold-header {
    font-weight: bold;
    color: black;
    /* background-color: azure; */
}

/* 设置容器的样式 */
/* 设置容器的样式 */
.container {
    /* 使用flex布局，让子元素水平排列 */
    display: flex;
    /* 设置容器的宽度，可以根据需要调整 */
    width: 600px;
    /* 设置容器的边距，可以根据需要调整 */
    margin: 10px 0;
    /* 设置容器的左边距为0，使其靠左 */
    margin-left: 0;
}
</style>
